package com.aliang.shopping.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliang.shopping.common.Result;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.config.PayConfig;
import com.aliang.shopping.exception.DataException;
import com.aliang.shopping.log.annotation.OperateLog;
import com.aliang.shopping.log.enums.OperateType;
import com.aliang.shopping.model.enums.OrdersStatusEnum;
import com.aliang.shopping.model.po.OrdersInfo;
import com.aliang.shopping.service.OrdersInfoService;
import com.aliang.shopping.service.OrdersItemService;
import com.aliang.shopping.util.ali.OssTemplate;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RequestMapping("/ali")
@RestController
@Api
@AllArgsConstructor
@Slf4j
public class ALiController {

    private OssTemplate ossTemplate;

    @PostMapping("/uploadImage")
//    @PreventRepeatSubmit(expireTime = 100,timeUnit = TimeUnit.MILLISECONDS)
    @ApiOperation("OSS上传图片")
    @OperateLog(title = "OSS上传图片", type = OperateType.OTHER)
    public Result<String> uploadImage(MultipartFile uploadImage) throws IOException {
        if (ObjectUtil.isEmpty(uploadImage)) {
            throw new DataException(ResultCodeEnum.DATA_LACK);
        }
        log.info("上传图片名称:{},开始时间{}", uploadImage.getOriginalFilename(), LocalDateTime.now());

        String imagePath = this.ossTemplate.upload(Objects.requireNonNull(uploadImage.getOriginalFilename()), uploadImage.getInputStream());
//        String imagePath = "https://picbed.aliang.asia/img/author.jpg";
        log.info("上传图片路径:{}", imagePath);
        return Result.ok(imagePath);
    }

    private PayConfig payConfig;
    private OrdersInfoService ordersInfoService;
    private OrdersItemService ordersItemService;

    /**
     * 支付宝支付异步回调
     */
    @PostMapping("/notify")
    public void payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, payConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                //获取支付编号
                String tradeNo = params.get("out_trade_no");
                //支付时间
                String gmtPayment = params.get("gmt_payment");
                //设置支付时间
                DateTime parse = DateUtil.parse(gmtPayment);
                LocalDateTime localDateTime = parse.toLocalDateTime();
                //更新订单状态
                this.ordersInfoService.update(
                        new LambdaUpdateWrapper<OrdersInfo>()
                                .set(OrdersInfo::getPayTime, localDateTime) //设置支付时间
                                .set(OrdersInfo::getStatus, OrdersStatusEnum.WAIT_DELIVERY.getCode()) // 设置订单状态待发货
                                .eq(OrdersInfo::getPayNo, tradeNo) //设置支付编号
                );
            }
        }
    }
}